package com.lora.web;

import com.acooly.core.common.dao.support.PageInfo;
import com.acooly.core.common.web.support.JsonEntityResult;
import com.acooly.core.common.web.support.JsonListResult;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.lora.entity.*;
import com.lora.enums.EquipmentEnum;
import com.lora.service.*;
import com.lora.util.FfmepgUtil;
import com.lora.util.MapUtil;
import com.lora.websocket.message.WebSockerSender;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/manage/demo/equipment")
public class EquipmentController {
    @Resource
    private EquipmentService equipmentService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private FfmepgUtil ffmepgUtil;
    /**
     * 设备设置
     * @return
     */
    @RequestMapping(value = "toequipment")
    public String toequipment(){
        return "/manage/equipment/equipment";
    }

    @RequestMapping(value = "equipmentEdit")
    public String equipmentEdit(Model model,HttpServletRequest request){

        List<Map<String, String>> equipments = EquipmentEnum.getEquipments();
        List<Map<String, String>> list = new ArrayList<>();
        for(Map<String, String> map:equipments){
            Map<String,String > m=new HashMap<>();
            for(String key : map.keySet()){
                String value = map.get(key);
                m.put("title",value);
                m.put("value",key);
                list.add(m);
            }
        }
        String id=request.getParameter("id");
        if(!id.equals("undefined")){
            Map<String,Object> map=new HashMap<>();
            map.put("id",id);
            List<Map<String, Object>> maps= equipmentService.query(map);
            model.addAttribute("equipment",maps.get(0));
        }


        //String position=(String) maps.get(0).get("position");
        //maps.get(0).put("position",position.substring(0,1));
        model.addAttribute("equipments",list);

        return "/manage/equipment/equipmentEdit";
    }
    /**
     * 设备报警
     * @return
     */
    @RequestMapping(value = "alarm")
    public String alarm(){
        return "/manage/equipment/alarmList";
    }
    /**
     * 设备参数
     * @return
     */
    @RequestMapping(value = "alarmParmentList")
    public String alarmParmentList(){
        return "/manage/equipment/alarmParmentList";
    }
    @RequestMapping(value = "alarmEdit")
    public String alarmEdit(Model model){
        List<Map<String, String>> equipments = EquipmentEnum.getEquipments();
        List<Map<String, String>> list = new ArrayList<>();
        for(Map<String, String> map:equipments){
            Map<String,String > m=new HashMap<>();
            for(String key : map.keySet()){
                String value = map.get(key);
                m.put("title",value);
                m.put("value",key);
                list.add(m);
            }
        }
        model.addAttribute("equipments",list);
        return "/manage/equipment/alarmEdit";
    }

    @ResponseBody
    @RequestMapping(value = "alarmdelete")
    public Map<String,Object> alarmdelete(String id){
        Map<String,Object> map=new HashMap<>();
        int i=equipmentService.alarmdelete(id);
        map.put("success",false);
        if(i>0){
            map.put("success",true);
        }

        return map;
    }
    @ResponseBody
    @RequestMapping(value = "alarmParmentdelete")
    public Map<String,Object> alarmParmentdelete(String id){
        Map<String,Object> map=new HashMap<>();
        int i=equipmentService.alarmParmentdelete(id);
        map.put("success",false);
        if(i>0){
            map.put("success",true);
        }
        return map;
    }
    @ResponseBody
    @RequestMapping(value = "delete")
    public Map<String,Object> delete(String id){
        Map<String,Object> map=new HashMap<>();
        List<Map<String, Object>> cam = jdbcTemplate.queryForList("select * from equipent where id="+id);
        if(cam.get(0).get("type").equals("13")){
            Process process = MapUtil.get(cam.get(0).get("eid").toString());
            if(process!=null){
                process.destroy();
            }
        }
        int i=equipmentService.delete(id);
        map.put("success",false);
        if(i>0){
            map.put("success",true);
        }
        return map;
    }
    @RequestMapping(value = "alarmParmentEdit")
    public String alarmParmentEdit(Model model,HttpServletRequest request){
        List<Map<String, String>> equipments = EquipmentEnum.getEquipments();
        String id = request.getParameter("id");
        String a="saveAlarmParment";
        if(!StringUtils.isBlank(id)){
            a="updateAlarmParment";
            Map<String,Object> m1=new HashMap<>();
            m1.put("id",id);
            List<Map<String, Object>> query = equipmentService.queryalarmParment(m1);
            if(query.size()>0)
            model.addAttribute("alarm",query.get(0));
        }

        model.addAttribute("save",a);
        List<Map<String, String>> list = new ArrayList<>();
        for(Map<String, String> map:equipments){
            Map<String,String > m=new HashMap<>();
            for(String key : map.keySet()){
                String value = map.get(key);
                m.put("title",value);
                m.put("value",key);
                list.add(m);
            }
        }
        model.addAttribute("equipments",list);
        return "/manage/equipment/alarmParmentEdit";
    }
    /**
     * 设备编号查询
     * @return
     */
    @RequestMapping(value = "equipmentList")
    @ResponseBody
    public JsonListResult<Map<String, Object>> equipmentList(HttpServletRequest request){
        JsonListResult<Map<String, Object>> result=new JsonListResult<>();
        Map<String,Object> map=new HashMap<>();
        String types=request.getParameter("equipment");
        String equipmenttype="";
        if(!StringUtils.isBlank(types)){
            String[] t=types.split("_");
            equipmenttype=t[0];
        }
        map.put("equipmenttype",equipmenttype);
        List<Map<String, Object>> query = equipmentService.query(map);
        result.setRows(query);
        result.setTotal(Long.valueOf(query.size()));
        return result;
    }

    /**
     * 报警查询
     * @return
     */
    @RequestMapping(value = "queryalarmParment")
    @ResponseBody
    public JsonListResult<Map<String, Object>> queryalarmParment(HttpServletRequest request){
        JsonListResult<Map<String, Object>> result=new JsonListResult<>();
        Map<String,Object> map=new HashMap<>();
        String types=request.getParameter("equipmenttype");
        String equipmenttype="";
        if(!StringUtils.isBlank(types)){
            String[] t=types.split("_");
            equipmenttype=t[0];
        }
        map.put("equipmenttype",equipmenttype);
        List<Map<String, Object>> query = equipmentService.queryalarmParment(map);
        result.setRows(query);
        result.setTotal(Long.valueOf(query.size()));
        return result;
    }
    /**
     * 报警查询
     * @return
     */
    @RequestMapping(value = "alarmList")
    @ResponseBody
    public JsonListResult<Map<String, Object>> alarmList(HttpServletRequest request){
        JsonListResult<Map<String, Object>> result=new JsonListResult<>();
        Map<String,Object> map=new HashMap<>();
        String types=request.getParameter("equipment");
        String equipmenttype="";
        if(!StringUtils.isBlank(types)){
            String[] t=types.split("_");
            equipmenttype=t[0];
        }
        map.put("equipmenttype",equipmenttype);
        List<Map<String, Object>> query = equipmentService.queryalarm(map);
        result.setRows(query);
        result.setTotal(Long.valueOf(query.size()));
        return result;
    }
    /**
     * 设备保存
     * @param request
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public JsonListResult<Map<String, Object>> save(HttpServletRequest request){
        JsonListResult<Map<String, Object>> result=new JsonListResult<>();
        Map<String,Object> map=new HashMap<>();
        String types=request.getParameter("type");
        String position=request.getParameter("position");
        String type="";
        String name="";

        if(!StringUtils.isBlank(types)){
            String[] t=types.split("_");
            type=t[0];
            name=t[1];
        }
        String eid=request.getParameter("eid");
        String parameter=request.getParameter("parameter");
        map.put("type",type);
        map.put("position",position);
        map.put("name",name);
        map.put("eid",eid);
        map.put("parameter",parameter);
        if(type.equals("13")){
            List<Map<String, Object>> service = jdbcTemplate.queryForList("select eid,position from equipent where type = 14");
            if(service!=null&&service.size()>0&&!service.get(0).get("eid").toString().isEmpty()){
                if(parameter!=null&&!parameter.trim().equals("")){
                    //开启摄像头推流方式;
                    String rstpurl="rtsp://admin:"+parameter.toString()+"@"+eid+":554/h264/ch1/sub/av_stream";
                    Object serpostion = service.get(0).get("position");
                    if (serpostion!=null&&!serpostion.toString().trim().equals("")){
                        ffmepgUtil.startFfm(eid,rstpurl,serpostion.toString());
                    }
                }
            }
        }
        equipmentService.save(map);
        return result;
    }
    /**
     * 设备编辑
     * @param request
     * @return
     */
    @RequestMapping(value = "update")
    @ResponseBody
    public JsonListResult<Map<String, Object>> update(HttpServletRequest request){
        JsonListResult<Map<String, Object>> result=new JsonListResult<>();
        Map<String,Object> map=new HashMap<>();
        String types=request.getParameter("type");
        String position=request.getParameter("position");
        String id=request.getParameter("id");
        String parameter=request.getParameter("parameter");
        String type="";
        String name="";

        if(!StringUtils.isBlank(types)){
            String[] t=types.split("_");
            type=t[0];
            name=t[1];
        }
        String eid=request.getParameter("eid");
        map.put("type",type);
        map.put("id",id);
        map.put("position",position);
        map.put("parameter",parameter);
        map.put("name",name);
        map.put("eid",eid);

        if(type.equals("13")){
            List<Map<String, Object>> service = jdbcTemplate.queryForList("select eid,position from equipent where type = 14");
            List<Map<String, Object>> cam = jdbcTemplate.queryForList("select * from equipent where id="+id);
            if(!cam.get(0).get("eid").toString().equals(eid)||!cam.get(0).get("parameter").toString().equals(parameter)){
                Process process = MapUtil.get(cam.get(0).get("eid").toString());
                if(process!=null){
                    process.destroy();
                }
                String rstpurl="rtsp://admin:"+parameter.toString()+"@"+eid+":554/h264/ch1/sub/av_stream";
                ffmepgUtil.startFfm(eid,rstpurl,service.get(0).get("position").toString());
            }
        }
        equipmentService.update(map);
        return result;
    }
    /**
     * 设备报警保存
     * @param request
     * @return
     */
    @RequestMapping(value = "saveAlarm")
    @ResponseBody
    public JsonListResult<Map<String, Object>> saveAlarm(HttpServletRequest request){
        JsonListResult<Map<String, Object>> result=new JsonListResult<>();
        Map<String,Object> map=new HashMap<>();
        String equipment=request.getParameter("equipment");
        String parment=request.getParameter("parment");
        String value=request.getParameter("value");
        String remarks=request.getParameter("remarks");
        String type="";
        String name="";

        if(!StringUtils.isBlank(equipment)){
            String[] t=equipment.split("_");
            type=t[0];
            name=t[1];
        }
        String eid=request.getParameter("eid");
        map.put("equipmenttype",type);
        map.put("equipmentname",name);
        map.put("parment",parment);
        map.put("value",value);
        map.put("remarks",remarks);
        equipmentService.saveAlarm(map);
        return result;
    }
    /**
     * 设备报警参数保存
     * @param request
     * @return
     */
    @RequestMapping(value = "saveAlarmParment")
    @ResponseBody
    public JsonListResult<Map<String, Object>> saveAlarmParment(HttpServletRequest request){
        JsonListResult<Map<String, Object>> result=new JsonListResult<>();
        Map<String,Object> map=new HashMap<>();
        String equipment=request.getParameter("equipment");
        String parameter=request.getParameter("parameter");
        String type="";
        String name="";

        if(!StringUtils.isBlank(equipment)){
            String[] t=equipment.split("_");
            type=t[0];
            name=t[1];
        }
        String eid=request.getParameter("eid");
        map.put("equipmenttype",type);
        map.put("equipmentname",name);
        map.put("parameter",parameter);
        equipmentService.saveAlarmParment(map);
        return result;
    }
    /**
     * 设备报警参数编辑
     * @param request
     * @return
     */
    @RequestMapping(value = "editAlarmParment")
    @ResponseBody
    public JsonListResult<Map<String, Object>> editAlarmParment(HttpServletRequest request){
        JsonListResult<Map<String, Object>> result=new JsonListResult<>();
        Map<String,Object> map=new HashMap<>();
        String equipment=request.getParameter("equipment");
        String parameter=request.getParameter("parameter");
        String id=request.getParameter("id");
        String type="";
        String name="";

        if(!StringUtils.isBlank(equipment)){
            String[] t=equipment.split("_");
            type=t[0];
            name=t[1];
        }
        String eid=request.getParameter("eid");
        map.put("equipmenttype",type);
        map.put("id",id);
        map.put("equipmentname",name);
        map.put("parameter",parameter);
        equipmentService.editAlarmParment(map);
        return result;
    }

    @Resource
    private WebSockerSender webSockerSender;
    @Resource
    private WirelesssmokefeelService wirelesssmokefeelService;
    @Resource
    private TemperaturehumidityService temperaturehumidityService;
    @Resource
    private InfraredinductionService infraredinductionService;
    @Resource
    private GateMahnetismService gateMahnetismService;
    @Resource
    private HumanActiveInfraredService humanActiveInfraredService;
    @Resource
    private ElectricityMeterService electricityMeterService;
    @Resource
    private SwitchingValueService switchingValueService;
    @Resource
    private UpsService upsService;
    @Resource
    private AirConditioningUpsService airConditioningUpsService;
    @Resource
    private FreshAirUpsService freshAirUpsService;

    /**
     * 加载每种设备的最后一条数据
     * @param eids
     * * @return
     */
    @RequestMapping(value = "fetchLastData")
    @ResponseBody
    public JsonEntityResult<String> fetchLastData(String eids) {
        JsonEntityResult<String> result = new JsonEntityResult<>();
        for(String eId : eids.split(",")) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("eid", eId);
            List<Map<String, Object>> query = equipmentService.query(map);
            Object obj = null;
            if(!query.isEmpty()) {
                String type = (String) query.get(0).get("type");
                EquipmentEnum equipmentEnum = EquipmentEnum.getEquipmentByType(type);
                Map<String, Boolean> sort = Maps.newHashMap();
                sort.put("id", false);
                Map<String, Object> search = Maps.newHashMap();
                search.put("EQ_equipmentid", eId);
                if(EquipmentEnum.WIRELESS_SMOKE_FEEL.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<Wirelesssmokefeel> pageInfo = new PageInfo<>();
                    PageInfo<Wirelesssmokefeel> query1 = wirelesssmokefeelService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                } else if(EquipmentEnum.TEMPERATURE_HUMIDITY.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<Temperaturehumidity> pageInfo = new PageInfo<>();
                    PageInfo<Temperaturehumidity> query1 = temperaturehumidityService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                } else if(EquipmentEnum.INFRARED_INDUCTION.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<Infraredinduction> pageInfo = new PageInfo<>();
                    PageInfo<Infraredinduction> query1 = infraredinductionService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                } else if(EquipmentEnum.GATE_MAGNETISM.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<GateMahnetism> pageInfo = new PageInfo<>();
                    PageInfo<GateMahnetism> query1 = gateMahnetismService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                } else if(EquipmentEnum.HUMAN_ACTIVE_INFRARED.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<HumanActiveInfrared> pageInfo = new PageInfo<>();
                    PageInfo<HumanActiveInfrared> query1 = humanActiveInfraredService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                } else if(EquipmentEnum.ELECTRICITY_METER.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<ElectricityMeter> pageInfo = new PageInfo<>();
                    PageInfo<ElectricityMeter> query1 = electricityMeterService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                } else if(EquipmentEnum.SWITCHING_VALUE.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<SwitchingValue> pageInfo = new PageInfo<>();
                    PageInfo<SwitchingValue> query1 = switchingValueService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                } else if(EquipmentEnum.UPS.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<Ups> pageInfo = new PageInfo<>();
                    PageInfo<Ups> query1 = upsService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                } else if(EquipmentEnum.AIR_CONDITIONING_UPS.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<AirConditioningUps> pageInfo = new PageInfo<>();
                    search.put("NOTNULL_heatingstate", null);
                    search.put("NOTNULL_airconditioningrunstate", null);
                    PageInfo<AirConditioningUps> query1 = airConditioningUpsService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                } else if(EquipmentEnum.FRESH_AIR_UPS.getValue().equals(equipmentEnum.getValue())) {
                    PageInfo<FreshAirUps> pageInfo = new PageInfo<>();
                    PageInfo<FreshAirUps> query1 = freshAirUpsService.query(pageInfo, search, sort);
                    if(!query1.getPageResults().isEmpty()) {
                        obj = query1.getPageResults().get(0);
                    }
                }
                if(obj != null) {
                    // 推送消息到前端
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    webSockerSender.sendMsgToAllClient(eId, JSONObject.toJSONString(obj), false);
                }
            }
        }
        result.setSuccess(false);
        return result;
    }
}
